package com.bluesmart.mia;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.Constants;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class AddProfileActivity extends BaseActivity implements OnClickListener {
	int mSex = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_profile);

		((TextView) findViewById(R.id.center)).setText(getString(R.string.add_profile));
		((Button) findViewById(R.id.right))
		.setCompoundDrawablesWithIntrinsicBounds(0, 0,
				R.drawable.a01, 0);

		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.camera).setOnClickListener(this);
		findViewById(R.id.text0).setOnClickListener(this);
		findViewById(R.id.text1).setOnClickListener(this);
		findViewById(R.id.text3).setOnClickListener(this);
		findViewById(R.id.text4).setOnClickListener(this);
		findViewById(R.id.male).setOnClickListener(this);
		findViewById(R.id.female).setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		switch(arg0.getId())
		{
		case R.id.left:
			finish();
			break;

		case R.id.right:
			sendHttpRequest();
			break;
			
		case R.id.camera:
			showImagePicker();
			break;
			
		case R.id.text0:
			showDate(R.id.text0);
			break;

		case R.id.text1:
			showDate(R.id.text1);
			break;
			
		case R.id.text3:
		{
			Intent intent = new Intent(this,AddProfileWeightActivity.class);
			startActivityForResult(intent, 10);
		}
			break;

		case R.id.text4:
		{
			Intent intent = new Intent(this,AddProfileHeightActivity.class);
			startActivityForResult(intent, 11);
		}
			break;
			
		case R.id.male:
			mSex = 1;
			((TextView)findViewById(R.id.male)).setTextColor(Color.parseColor("#32abbe"));
			((TextView)findViewById(R.id.female)).setTextColor(Color.WHITE);
			break;
			
		case R.id.female:
			mSex = 2;
			((TextView)findViewById(R.id.female)).setTextColor(Color.parseColor("#32abbe"));
			((TextView)findViewById(R.id.male)).setTextColor(Color.WHITE);
			break;
		}
	}
	
	void showImagePicker()
	{
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		
		OnClickListener listen = new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				if(arg0.getId() == R.id.cancel) mDialog.dismiss();
				else if(arg0.getId() == R.id.pic)
				{
					mDialog.dismiss();
					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType("image/*");
					startActivityForResult(getAlbum, 3);
				}
				else
				{
					mDialog.dismiss();
					Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
					startActivityForResult(intent, 4);
				}
			}
		};

		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(listen);
		mDialog.findViewById(R.id.pic).setOnClickListener(listen);
		mDialog.findViewById(R.id.cancel).setOnClickListener(listen);
		mDialog.show();
	
	}

	private File mPhotoFile;
	@SuppressWarnings({ "deprecation" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		Bitmap bitmap = null;
		if (resultCode == RESULT_OK) {
			if(requestCode == 10)
			{
				((TextView)findViewById(R.id.text3)).setText(data.getStringExtra("value"));
				return;
			}
			
			if(requestCode == 11)
			{
				((TextView)findViewById(R.id.text4)).setText(data.getStringExtra("value"));
				return;
			}
			
			if (requestCode == 4) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			((ImageView) findViewById(R.id.icon)).setImageBitmap(bitmap);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
	
	void showDate(final int index)
	{
		Calendar calendar = Calendar.getInstance();
		
		DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int day) {
            	String date = new StringBuilder().append(year).append("-")
                        .append((month + 1) < 10 ? "0" + (month + 1) : (month + 1))
                        .append("-")
                        .append((day < 10) ? "0" + day : day).toString();
            	
            	((TextView)findViewById(index)).setText(date);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
        calendar.get(Calendar.DAY_OF_MONTH) );
		dialog.setTitle(getString(R.string.choose_date));
		dialog.show();
	}
	
	public void sendGetBabyRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				((DemoApp)getApplicationContext()).mBabyList = JSON.parseArray(response);
				if(((DemoApp)getApplicationContext()).mBabyList != null)
				{
					int count = ((DemoApp)getApplicationContext()).mBabyList.size();
					for(int i = 0; i < count; i++)
					{
						JSONObject item = ((DemoApp)getApplicationContext()).mBabyList.getJSONObject(i);
						if(item.getString("isCurr").equals("true")) ((DemoApp)getApplicationContext()).mSelectedBaby = i;
					}
					
					startActivity(new Intent(AddProfileActivity.this,BabyMilkBottleActivity.class));
					finish();
				}
			}
		};
		
		String username = PreferencesUtils.getString(this, "username");
		String password = PreferencesUtils.getString(this, "password");
		if(username == null || username.length() == 0)
		{
			username = PreferencesUtils.getString(this, "username_tmp");
			password = PreferencesUtils.getString(this, "password_tmp");
		}
		
		JSONObject params = new JSONObject();
		params.put("mia_un",username);
		params.put("pwd", password);
		params.put("handType", "get");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	private void sendHttpRequest() {
		String expected = ((TextView)findViewById(R.id.text0)).getText().toString();
		String birth = ((TextView)findViewById(R.id.text1)).getText().toString();
		String nick = ((EditText)findViewById(R.id.text2)).getText().toString();
		String weight = ((TextView)findViewById(R.id.text3)).getText().toString();
		String height = ((TextView)findViewById(R.id.text4)).getText().toString();
		/*
		if(expected.length() == 0 || birth.length() == 0 || nick.length() == 0
				|| weight.length() == 0 || height.length() == 0 || mSex == 0)
		{
			ToastUtil.showToastWithAlertPic(R.string.add_profile_tip);
			return;
		}*/
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					String babyid = ruser.getString("babyid");
					PreferencesUtils.putString(getApplicationContext(), "babyid", babyid);
					if(mPhotoFile == null)
					{
						sendGetBabyRequest();
						
						String username = PreferencesUtils.getString(AddProfileActivity.this, "username");
						if(username == null || username.length() == 0)
						{
							finish();
						}
					}
					else
					{
						sendHttpImgRequest(babyid);
					}
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else 
				{
				}
			}
		};
		
		if(height.length() > 0) height = height.substring(0, height.length() - 2);
		if(weight.length() > 0) weight = weight.substring(0, weight.length() - 2);
		
		String username = PreferencesUtils.getString(this, "username");
		String password = PreferencesUtils.getString(this, "password");
		if(username == null || username.length() == 0)
		{
			username = PreferencesUtils.getString(this, "username_tmp");
			password = PreferencesUtils.getString(this, "password_tmp");
		}

		JSONObject params = new JSONObject();
		params.put("mia_un", username);
		params.put("pwd", password);
		params.put("handType","add");
		params.put("nickname", nick);
		params.put("sex", mSex==1?"boy":"girl");
		params.put("bexpected", expected);
		params.put("bday", birth);
		params.put("height", height);
		params.put("weight", weight);
		try
		{
			params.put("deviceid", getIntent().getStringExtra("deviceid"));
		}
		catch(Exception e)
		{
			
		}
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	private void sendHttpImgRequest(String babyId) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					sendGetBabyRequest();
					
					String username = PreferencesUtils.getString(AddProfileActivity.this, "username");
					if(username == null || username.length() == 0)
					{
						finish();
					}
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else 
				{
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("babyid", babyId);
		try {
			params.put("filename", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		MgqRestClient.post(Constant.SERVER_URL + "/sw/uploadimg.ashx", params, loginHandler);
	}
}
